package com.bytz.modules.cms.order.service.impl;

import com.bytz.common.exception.BytzBootException;
import com.bytz.modules.cms.common.service.CmsConfigService;
import com.bytz.modules.cms.order.entity.Order;
import com.bytz.modules.cms.order.entity.OrderItem;
import com.bytz.modules.cms.order.model.OrderItemModel;
import com.bytz.modules.cms.order.model.OrderModel;
import com.bytz.modules.cms.order.service.IMallOrderService;
import com.bytz.modules.cms.order.service.IOrderCopyService;
import com.bytz.modules.cms.order.service.IOrderItemService;
import com.bytz.modules.cms.order.service.IOrderService;
import com.bytz.modules.cms.product.constant.ProductConstants;
import com.bytz.modules.cms.product.model.ProductModel;
import com.bytz.modules.cms.product.service.IMallProductService;
import com.bytz.modules.cms.reseller.entity.EndUser;
import com.bytz.modules.cms.reseller.model.ResellerSalesModel;
import com.bytz.modules.cms.reseller.service.IEndUserService;
import com.bytz.modules.cms.reseller.service.IResellerSalesService;
import com.bytz.modules.cms.reseller.util.ResellerSecurityUtils;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class OrderCopyServiceImpl implements IOrderCopyService {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderItemService orderItemService;

    @Autowired
    private IMallProductService productService;

    @Autowired
    private IEndUserService endUserService;

    @Autowired
    private IMallOrderService mallOrderService;

    @Autowired
    private IResellerSalesService salesService;

    @Autowired
    private CmsConfigService configService;

    @Override
    public OrderModel copyOrder(String id) {

        String resellerId = ResellerSecurityUtils.getUserId();

        Order order = orderService.getById(id);
        List<OrderItem> items = orderItemService.getByOrderId(id);

        OrderModel newOrder = new OrderModel();
        newOrder.setOrderType(order.getOrderType());
        newOrder.setProjectName(order.getProjectName());
        newOrder.setCopyFromOrderId(id);

        Map<String, EndUser> endUserMap = endUserService.getByIds(Sets.newHashSet(order.getDemanderId(), order.getEndUserId(), order.getShipToId()))
                .stream().collect(Collectors.toMap(EndUser::getId, t -> t));

        newOrder.setSupplierFax(order.getSupplierFax());
        newOrder.setDemanderPhone(order.getDemanderPhone());
        newOrder.setSupplierPostcode(order.getSupplierPostcode());
        newOrder.setDeliveryPlan(order.getDeliveryPlan());
        newOrder.setAttachment(order.getAttachment());
        newOrder.setRemark(order.getRemark());

        // 复制需方信息
        EndUser demander = endUserMap.get(order.getDemanderId());
        if (demander != null) {
            newOrder.setDemanderId(demander.getId());
            newOrder.setDemanderNumber(demander.getCustomerNumber());
            newOrder.setDemanderName(demander.getCustomerName());
            newOrder.setDemanderAddress(demander.getAddress());
        }
        newOrder.setDemanderPostcode(order.getDemanderPostcode());
        newOrder.setDemanderAgent(order.getDemanderAgent());
        newOrder.setDemanderFax(order.getDemanderFax());

        // 复制终端用户信息
        EndUser endUser = endUserMap.get(order.getEndUserId());
        if (endUser != null) {
            newOrder.setEndUserId(endUser.getId());
            newOrder.setEndUserNumber(endUser.getCustomerNumber());
            newOrder.setEndUserName(endUser.getCustomerName());
            newOrder.setEndUserAddress(endUser.getAddress());
            newOrder.setEndUserPhone(endUser.getPhone());
            newOrder.setEndUserContact(endUser.getContactPerson());
        }

        // 复制shipTo
        EndUser shipTo = endUserMap.get(order.getShipToId());
        if (shipTo != null) {
            newOrder.setShipToId(shipTo.getId());
            newOrder.setShipToNumber(shipTo.getCustomerNumber());
            newOrder.setShipToName(shipTo.getCustomerName());
            newOrder.setShipToAddress(order.getShipToAddress());
            newOrder.setShipToPhone(order.getShipToPhone());
            newOrder.setShipToContact(order.getShipToContact());
        }

        // 复制销售
        ResellerSalesModel sale = salesService.getSalesByResellerIdAndSaleId(order.getSalesId(), resellerId);
        if (sale != null) {
            newOrder.setSalesId(sale.getSalesId());
            newOrder.setSalesName(sale.getSalesName());
            newOrder.setSalesExternalId(sale.getSalesExternalId());
        }

        // 复制商品
        Set<String> productNumbers = items.stream().map(OrderItem::getProductNumber).collect(Collectors.toSet());
        Map<String, ProductModel> productModelMap = productService.getProductDetailByNumbers(productNumbers)
                .stream().collect(Collectors.toMap(ProductModel::getProductNumber, t -> t));

        BigDecimal taxRate = configService.getGlobal().getTaxRate();

        List<OrderItemModel> newItems = items.stream().map(item -> {
            ProductModel productModel = productModelMap.get(item.getProductNumber());
            if (productModel == null || !ProductConstants.ProductStatus.ENABLE.equals(productModel.getStatus())) {
                throw new BytzBootException(String.format("商品【%s】已下架，无法复制订单", item.getProductNumber()));
            }
            OrderItemModel newItem = new OrderItemModel();

            newItem.setOrderId(newOrder.getId());
            newItem.setProductNum(item.getProductNum());
            newItem.setNegotiatePrice(item.getNegotiatePrice());

            newItem.setDeliveryDate(productModel.getDeliveryDate());
            newItem.setNoTaxPrice(productModel.getCalculatePrice());
            newItem.setProductId(productModel.getId());
            newItem.setProductNumber(productModel.getProductNumber());
            newItem.setProductDesc(productModel.getMaterialDesc());
            if (productModel.getCalculatePrice() != null) {
                newItem.setIncludeTaxPrice(productModel.getCalculatePrice().multiply(BigDecimal.ONE.add(taxRate)));
            }
            if (newItem.getNegotiatePrice() != null){
                newItem.setTotalTaxPrice(newItem.getNegotiatePrice().multiply(BigDecimal.valueOf(newItem.getProductNum())));
            } else {
                newItem.setTotalTaxPrice(newItem.getIncludeTaxPrice().multiply(BigDecimal.valueOf(newItem.getProductNum())));
            }

            return newItem;
        }).collect(Collectors.toList());
        newOrder.setOrderItemList(newItems);

        // 暂存新的订单
        return mallOrderService.saveOrder(newOrder);
    }
}
